package common.controls.item
{
	
	import common.controls.item.events.ItemEvent;
	import common.controls.utils.MathUtils;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	
	/**  
	 * 
	 * @author carrey
	 * */ 
	public class ItemShortcut extends Item
	{
		private var _bitmap:Bitmap;
		private var _bitmapData:BitmapData;
		
		private var _parentItem:Item;
		
		public function ItemShortcut()
		{
			super();
		}
		
		override protected function init():void
		{
		}
		
		override public function destroy():void
		{
			super.destroy();
			if( _bitmap != null )
			{
				_bitmap.bitmapData = null;
				_bitmap = null;
				_bitmapData.dispose();
				_bitmapData = null;
			}
			if( _parentItem != null )
			{
				_parentItem.removeEventListener( ItemEvent.ITEM_SHAPE_CHANGE, onItemShapeChange );
				_parentItem = null;
			}
		}
		
		override public function setSize(w:int, h:int):void
		{
			super.setSize( w, h );
			
			var arr:Array = MathUtils.scaleFit( _bitmap.width, _bitmap.height, w, h );
			_bitmap.smoothing = true;
			_bitmap.width = arr[0];
			_bitmap.height = arr[1];
		}
		
		internal function setParentItem( item:Item ):void
		{
			if( _parentItem != null )
			{
				//这个只能设置一次
				throw new Error( "ItemShortcut的parentItem不允许多次赋值" );
			}
			_parentItem = item;
			
			_bitmapData = new BitmapData( item.width, item.height, true, 0 );
			_bitmap = new Bitmap( _bitmapData );
			_container.addChild( _bitmap );
			
			_width = item.width;
			_height = item.height;
			
			onItemShapeChange( null );
			_parentItem.addEventListener( ItemEvent.ITEM_SHAPE_CHANGE, onItemShapeChange, false, 0, true );
		}
		
		public function get parentItem():Item
		{
			return _parentItem;
		}
		
		private function onItemShapeChange( e:ItemEvent ):void
		{
			_bitmapData.fillRect( new Rectangle(0, 0, _bitmapData.width, _bitmapData.height), 0 );
			_bitmapData.draw( _parentItem );
		}
	}
}